package com.example.flag03;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class mine extends AppCompatActivity {
    private List<MineItem> itemsList = new ArrayList<>();
    //    数据库变量
    private MyDatabaseHelper databaseHelper;
    //    时间
    private int nowYear;
    private int nowMonth;
    private int nowDay;
    private int lastYear;
    private int lastMonth;
    private int lastLastYear;
    private int lastLastMonth;
//    总的Flags数
    private int allFlags=0;
//    总的已完成Flags数
    private int allFinishedFlags=0;
//    总的待完成Flags数
    private int allUnfinishedFlags=0;
//    上个月完成Flags数
    private int lastMonthFinishedFlags=0;
//    上个月过期Flags数
    private int lastMonthUnfinishedFlags=0;
//    上个月发布的Flags数
    private int lastFlags=0;
//    上上个月过期Flags数
    private int lastLastMonthUnfinishedFlags=0;
//    上上个月完成Flags数
    private int lastLastMonthFinishedFlags=0;
//    上上个月发布Flags数
    private int lastLastMonthFlags=0;
    //    创建日历对象
    Calendar calendar = Calendar.getInstance();
//    积分
    private int grade=0;
//    名字
    private String name;
//    头像
    private ImageView TuoXian;
//    报告
    private String report;
//    更换头像
    private static final int REQUEST_CODE_CHOOSE=0;
//    二维码图片
    private Bitmap codeBitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);

//      到当前的年月日
        nowYear = calendar.get(Calendar.YEAR);
        nowMonth = calendar.get(Calendar.MONTH) + 1;
        nowDay = calendar.get(Calendar.DAY_OF_MONTH);

//       设置数据
        getData();

//      初始化数据
        initData();

//       数组适配器
        MineItemAdapter mineItemAdapter=new MineItemAdapter(mine.this,R.layout.layout1,itemsList);
        ListView listview = (ListView) findViewById(R.id.listView);
        listview.setAdapter(mineItemAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView listView1 = (ListView) parent;
                MineItem item = (MineItem) listView1.getItemAtPosition(position);
                if(item.getNumber()==-1){
                    //        弹窗提示
                    final AlertDialog.Builder builder = new AlertDialog.Builder(mine.this);
                    builder.setTitle("月报");
                    builder.setCancelable(false);
                    builder.setMessage(report);
                    builder.setPositiveButton("分享", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
//                            生成二维码
                        codeBitmap = EncodingUtils.createQRCode(report,500,500,null);
//
                            saveBitmap();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    AlertDialog alertDialog = builder.create();
                    alertDialog.show();
                    Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    Button negativeButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
                    positiveButton.setPadding(2,0,2,0);
                    positiveButton.setBackgroundResource(R.drawable.button_shape);
                    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
                    layoutParams.weight = 10;
                    positiveButton.setLayoutParams(layoutParams);
                    negativeButton.setLayoutParams(layoutParams);
                }
            }
        });

//        设置积分
        TextView gradeView=(TextView) findViewById(R.id.gradeNumber);
        grade=allFinishedFlags*5-allUnfinishedFlags*3+10;
        gradeView.setText(String.valueOf(grade));

//        设置打卡称号  grade 100以下打卡萌新  100-500打卡达人  500以上 打卡大神
        TextView name=(TextView)findViewById(R.id.name1);
        if(grade<100){
            name.setText("打卡萌新");
        }else if(grade>=100&&grade<500){
            name.setText("打卡达人");
        }else {
            name.setText("打卡大神");
        }

    }

//    授权返回值
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull  int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==0){
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else {
                Toast.makeText(this,"你没有访问相册权限~",Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode==1){
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                EncodingUtils.saveBitmap(mine.this,codeBitmap);
            }else {
                Toast.makeText(this,"你没有访问相册权限~",Toast.LENGTH_SHORT).show();
            }
         }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data==null){
            Log.d("展示失败0000000000000","23345");
            Toast.makeText(this,"数据为空！",Toast.LENGTH_SHORT).show();
            return;
        }else {
            if (requestCode == REQUEST_CODE_CHOOSE) {
                if (Build.VERSION.SDK_INT < 19) {
                    Uri uri = data.getData();
                    String imagePath = getImagePath(uri, null);
                    displayImage(imagePath);
                } else {
                    handleImageOnApi19(data);
                    Log.d("handleImageOnApi19","失败");
                }
            }
        }
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            Bitmap bitmap1=EncodingUtils.createCircleImage(bitmap,50,50,25,1);
            TuoXian.setImageBitmap(bitmap1);
//            保存到数据库
            String bitmapToString = EncodingUtils.bitmapToString(bitmap1);
            SPUtils.put(mine.this,"TouXian",bitmapToString);
            Log.d("展示成功","000000");
        } else {
            Log.d("展示失败","23345");
        }
    }

    private String getImagePath(Uri uri , String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String documentId = DocumentsContract.getDocumentId(uri);
            Log.d("documentId ",documentId );

            if(TextUtils.equals(uri.getAuthority(),"com.android.providers.media.documents")){
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID+"="+id;
                imagePath = getImagePath(uri,selection);
                Log.d("路径",imagePath);
            }else if(TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")){
                Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(documentId));
                imagePath=getImagePath(contentUri,null);
            }

        }else if("content".equalsIgnoreCase(uri.getScheme())){
            imagePath=getImagePath(uri,null);
        }else if("file".equalsIgnoreCase(uri.getScheme())){
            imagePath=uri.getPath();
        }
        displayImage(imagePath);
    }

//      修改头像
    public void choosePhoto(View view) {

        //        弹窗提示
        final AlertDialog.Builder builder = new AlertDialog.Builder(mine.this);
        builder.setTitle(null);
        builder.setCancelable(false);
        builder.setMessage("是否更换头像？");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                if(ContextCompat.checkSelfPermission(mine.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
                    //选择图片
                    openAlbum();
                } else{
                    ActivityCompat.requestPermissions(mine.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0);
                    //获取权限
                }
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        Button negativeButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
        layoutParams.weight = 10;
        positiveButton.setLayoutParams(layoutParams);
        negativeButton.setLayoutParams(layoutParams);
    }

    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,REQUEST_CODE_CHOOSE);
    }


    //        保存二维码
    private void saveBitmap(){
        //          动态加载布局文件，得到相应的View对象
        View view1 = View.inflate(this, R.layout.layout3, null);
        //                        获取相应的控件ID
        ImageView imageView=(ImageView)view1.findViewById(R.id.codeBitmap);
        imageView.setImageBitmap(codeBitmap);

        final AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.layout01);
        builder.setTitle("分享二维码");
        builder.setView(view1);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//              保存二维码
                if(ContextCompat.checkSelfPermission(mine.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED){
                    //保存图片
                    EncodingUtils.saveBitmap(mine.this,codeBitmap);
                } else{
                    ActivityCompat.requestPermissions(mine.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                    //获取权限
                }
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        Button positiveButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
        Button negativeButton = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        positiveButton.setPadding(2,2,2,2);
        negativeButton.setPadding(2,2,2,2);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) positiveButton.getLayoutParams();
        layoutParams.weight = 10;
        positiveButton.setLayoutParams(layoutParams);
        negativeButton.setLayoutParams(layoutParams);
    }

    //        修改名字
    public void reverseName(View view) {
         XiuGaiName dialog = new XiuGaiName(mine.this);
         dialog.show();
         dialog.setDialogSize();
         dialog.setOnEnsureListener(new XiuGaiName.OnEnsureListener() {
             @Override
             public void onEnsure() {
                 name = dialog.getEditText();
                 if (!name.equals(null)) {
                     TextView textView = (TextView) findViewById(R.id.name);
                     textView.setText(name);
                     SPUtils.put(mine.this,"name",name);
                 }
                 dialog.cancel();
             }
         });
    }

    //       获取数据
    private void getData() {
        //创建数据库的对象
        databaseHelper = new MyDatabaseHelper(this, "FlagData.dp", null, 1);
        //初始化数据库
        SQLiteDatabase db = databaseHelper.getWritableDatabase();
        Cursor cursor = db.query("Flag", null, "signal=" + 1, null, null, null, null);
        allFinishedFlags=cursor.getCount();

        cursor = db.query("Flag", null, "signal=" + -1, null, null, null, null);
        allUnfinishedFlags=cursor.getCount();

        cursor = db.query("Flag", null, null, null, null, null, null);
        allFlags=cursor.getCount();
        cursor.close();

//       上上个月的时间
        lastLastMonth=nowMonth-2;
        if(lastLastMonth==0){
            lastLastYear=lastLastYear-1;
            lastLastMonth=12;
        }

//       爬取上上个月完成，过期，发布数
        Cursor cursor4 = db.query("Flag1", null, "Year=" + lastLastYear + " AND Month=" + lastLastMonth , null, null, null, null);
        if(cursor4.getCount()!=0) {
            cursor4.moveToFirst();
            lastLastMonthFinishedFlags = cursor4.getInt(cursor4.getColumnIndex("finish"));
            lastLastMonthUnfinishedFlags = cursor4.getInt(cursor4.getColumnIndex("out"));
            lastLastMonthFlags = cursor4.getInt(cursor4.getColumnIndex("give"));
        }
        cursor4.close();

//       上个月的时间
        lastMonth=nowMonth-1;
        lastYear=nowYear;
        if(lastMonth==0){
            lastYear=nowYear-1;
            lastMonth=12;
        }

//        完成，过期，发布
//        判断是否记录上个月的完成，过期，发布个数，月报
        Cursor cursor1 = db.query("Flag1", null, "Year=" + lastYear + " AND Month=" + lastMonth , null, null, null, null);
        if(cursor1.getCount()==0){
//            否，爬取，上传
            int give,out,finish;

//            上个月发布个数
            Cursor  cursor2 = db.query("Flag", null, "fromYear=" + lastYear + " AND fromMonth=" + lastMonth , null, null, null, null);
            give=cursor2.getCount();

//            上个月完成个数
            cursor2 = db.query("Flag", null, "finishedYear=" + lastYear + " AND finishedMonth=" + lastMonth + " AND signal=" + 1, null, null, null, null);
            finish=cursor2.getCount();

//            上个月过期个数
            cursor2 = db.query("Flag", null, "finishedYear=" + lastYear + " AND finishedMonth=" + lastMonth + " AND signal=" + -1, null, null, null, null);
            out=cursor2.getCount();

//            月报
            report="你在"+lastYear+"年"+lastMonth+"月中共发布"+give+"个Flags，完成了"+finish+"个Flags，共有"+out+"个Flag过期，比上个月多发布了"+lastLastMonthFlags+"个Flags，多完成了"+lastLastMonthFinishedFlags+"个，过期数增加了"+lastLastMonthUnfinishedFlags+
                    "个。人在旅途，难免会遇到荆棘和坎坷，但风雨过后，一定会有美丽的彩虹。加油，追梦人！";

//            储存到表Flag1
            ContentValues values = new ContentValues();
            values.put("Year",lastYear);
            values.put("Month",lastMonth);
            values.put("give",give);
            values.put("out",out);
            values.put("finish",finish);
            values.put("report",report);
            db.insert("Flag1",null,values);
        }


//      爬取上个月完成，过期，发布数
        Cursor cursor3 = db.query("Flag1", null, "Year=" + lastYear + " AND Month=" + lastMonth , null, null, null, null);
        if(cursor3.getCount()!=0) {
            cursor3.moveToFirst();
            lastMonthFinishedFlags = cursor3.getInt(cursor3.getColumnIndex("finish"));
            lastMonthUnfinishedFlags = cursor3.getInt(cursor3.getColumnIndex("out"));
            lastFlags = cursor3.getInt(cursor3.getColumnIndex("give"));
            report=cursor3.getString(cursor3.getColumnIndex("report"));
        }
        cursor3.close();
    }

    //       初始化数据
    private void initData() {
        MineItem item1=new MineItem("总的Flags数",R.drawable.more,allFlags);
        MineItem item2=new MineItem("总的已完成Flags数",R.drawable.more,allFinishedFlags);
        MineItem item3=new MineItem("总的过期Flags数",R.drawable.more,allUnfinishedFlags);
        MineItem item4=new MineItem("上个月发布Flags数",R.drawable.more,lastFlags);
        MineItem item5=new MineItem("上个月已完成Flags数",R.drawable.more,lastMonthFinishedFlags);
        MineItem item6=new MineItem("上个月过期Flags数",R.drawable.more,lastMonthUnfinishedFlags);
        MineItem item7=new MineItem("查看月报",R.drawable.more,-1);
        itemsList.add(item1);
        itemsList.add(item2);
        itemsList.add(item3);
        itemsList.add(item4);
        itemsList.add(item5);
        itemsList.add(item6);
        itemsList.add(item7);

//        获取名字
        name=SPUtils.get(mine.this,"name","name").toString();
        TextView textView=(TextView)findViewById(R.id.name);
        textView.setText(name);

//        获取头像
        String string=SPUtils.get(mine.this,"TouXian","TouXian").toString();
        TuoXian = findViewById(R.id.image);
        if(!string.equals(null)) {
            Bitmap bitmap = EncodingUtils.stringToBitmap(string);
            Bitmap bitmap1=EncodingUtils.createCircleImage(bitmap,50,50,25,2);
            TuoXian.setImageBitmap(bitmap1);
        }else {
            Bitmap bitmap = EncodingUtils.getBitmapFromDrawable(getResources().getDrawable(R.drawable.ye));
            Bitmap bitmap1=EncodingUtils.createCircleImage(bitmap,50,50,25,1);
            TuoXian.setImageBitmap(bitmap1);
        }
    }


}